<script setup lang='ts'>
// 自定义 规则
interface selectorItem {
    label: string,
    id: string
}

import { ref, reactive } from 'vue';
import { https } from '@/api/api'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { showToast, navigateTo, upload, currentLocation } from '@/public/index'
import Bottom from '@/components/bottom/index.vue'
import { useMarkerStore, useMapStore } from '@/store/index'
import AliIcon from '@/components/AliIcon/index.vue'
import { colorList } from '../list';
const Map = require('../../public/amap/mapWx.js')
// const bg_url = import.meta.env.VITE_BASE_URL
const markerStore = useMarkerStore();
const mapStore = useMapStore();

// 显示大小
const isShowSize = ref(false);
const columns: Array<Array<selectorItem>> = reactive([[{ label: '大', id: '0' }, { label: '中', id: '1' }, { label: '小', id: '2' }]]);
// 类型 
const type = ref<'add' | 'edit' | 'applyForChanges'>('add'); // add：添加；edit:修改；applyForChanges：申请变更
//选择颜色
const isColor = ref(false);
// 选中的颜色id
const colorId = ref<string>('0');
const aloneChecked = ref(false);
// 用户当前的地理位置
const cLngLat = ref<string | undefined>(undefined);
// form 表单
const fromRef = ref();
// 手机号 是否 通过校验规则
const isPhone = ref(false);
// 是否查询出用户
const isQuerUser = ref<string>('') // true:查询出来了 false:'未查询出'
// 修改添加的请求name 
const apiNameArr = reactive({
    'add': 'apiAddMarker',
    'edit': 'apiUpdateMarker',
    'applyForChanges': 'apiApplyUpdateMarker'
})
/**
 * @property 变量
 */
const rules = {
    phone: {
        type: 'string',
        trigger: ['change'],
        required: false,
        validator: (_: any, value: string) => {
            if (value.length === 0) return true;
            return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)
        },
        message: '电话格式输入错误'
    },
    alias: {
        type: 'string',
        trigger: ['change', 'blur'],
        required: true,
        message: '请输入名称'
    },
}

/**
 * @property  所有请求以api开头 如:apiDataInfo
 */
const apiHttps = async (apiName: string, imgs: Array<string>) => {
    if (!apiName) {
        showToast('apiName:error 请联系管理员处理');
        return {
            code: 404,
            data: null,
        }
    }
    const data: any = {};
    Object.entries(markerStore.marker).forEach((item: [string, any]) => {
        if (typeof item[1] === 'number') data[item[0]] = item[1] + '';
        else data[item[0]] = item[1]
    })
    let lotlng: {
        lng: undefined | string,
        lat: undefined | string
    } | false = {
        lng: undefined,
        lat: undefined
    };

    lotlng = await currentLocation();
    await clickGetPosition();
    if (!lotlng) {
        return {
            code: -1,
            data: {
                msg: '请同意使用地址服务'
            },
        }
    }
    let apiData = {}
    if (type.value === 'applyForChanges') {
        apiData = {
            mid: data.mid,
            alias: data.alias,
            clng: lotlng?.lng,
            clat: lotlng?.lat,
            ctoponym: cLngLat.value,
            toponym: data.toponym,
            list: JSON.stringify(imgs),
            name: data.name,
            phone: data.phone,
            showsize: colorId.value,

        }
    }
    if (type.value === 'add') {
        apiData = {
            ...data,
            ctoponym: cLngLat.value,
            list: JSON.stringify(imgs),
            team: uni.getStorageSync('userData')?.team + '',
            showsize: colorId.value,
            clng: lotlng?.lng,
            clat: lotlng?.lat,
        }
    }
    const res = await https({
        mode: 'marker',
        name: apiName,
        data: apiData
    })
    return res
}
// 通过手机号查询商户是否存在数据库中
const apiQueryPhone = async () => {
    const res = await https({
        mode: 'public',
        name: 'apiGetInfoThroughPhone',
        data: {
            phone: markerStore.marker.phone
        }
    })
    isQuerUser.value = res.code === 0 ? 'true' : 'false'
    if (res.code !== 0 && res.data.msg) return showToast(res.msg);
    markerStore.marker.name = res.data?.info?.name || markerStore.marker.name;
    markerStore.marker.alias = res.data?.info?.alias || markerStore.marker.alias;
}
// 申请变更
/**
 * @property 自定义事件 以事件名开头 如: clickButton,inputDev
 */
// 创建标记点
const addMarker = async () => {
    if (!aloneChecked.value) {
        uni.showModal({
            title: '温馨提示',
            content: '请先同意用户隐私政策和用户服务协议'
        })
        return;
    }
    uni.setStorageSync('aloneChecked', aloneChecked.value);
    if (type.value === 'add') {
        delete markerStore.marker.mid
    }
    delete markerStore.marker.iscreator
    delete markerStore.marker.notes
    await fromRef.value.validate();
    if (markerStore.picList.length === 0) return showToast('请您上传图片')
    uni.showLoading({
        title: '加载中',
        mask: true
    })
    const promiseAll: any = [];
    markerStore.picList.forEach(item => {
        promiseAll.push(upload(item, 'UploadMarkerImg'));
    })
    const p = Promise.all(promiseAll);
    const fileRef = await p;
    const imgs = fileRef.map(item => item.file);
    if (imgs.includes(null) || imgs.includes('null')) return showToast('图片上传失败，请重试')
    const res = await apiHttps(apiNameArr?.[type.value], imgs)
    uni.hideLoading();
    showToast(res.data.msg)

    if (res.code !== 0) return;

    mapStore.updataRefresh(true);
    // 创建 新的标记点
    if (type.value === 'add') {
        delete res.data.msg;
        markerStore.markersList.push({
            ...res.data,
            showsize: colorId.value
        })
        markerStore.updataMarker({showsize:colorId.value})
    }
    setTimeout(() => {
        markerStore.setPicList([]);
        markerStore.updataMarker(res.data);
        // 销毁当前页面 跳转回访记录
        navigateTo('/pages/editNotepad/index', 2);
    }, 2000)
}
const afterRead = (e: { file: Array<Files> }) => {
    markerStore.picList.push(...e.file)
}

const deletePic = (e: { index: number }) => {
    // 通过下标进行删除
    markerStore.picList = markerStore.picList.filter((item, i) => i !== e.index)
}
// 超出限制大小
const oversize = () => {
    showToast('图片不可大于2M');
}
const clickConfirm = (e: { value: Array<selectorItem> }) => {
    markerStore.updataMarker({
        showsize: e.value[0].id
    })
    isShowSize.value = false
}
// 获取他当前位置信息
const clickGetPosition = async (): Promise<LngLat> => {
    const { lat, lng } = await currentLocation() as LngLat;
    return new Promise(reslove => {
        Map.reverseGeocoder({
            location: {
                latitude: lat,
                longitude: lng,
            },
            get_poi: 1,
            success: (res: any) => {
                cLngLat.value = res.result.address
                reslove({ lat, lng });
            },
            fail: (error: { message: string }) => {
                cLngLat.value = error.message
                showToast(error.message)
                reslove({ lat, lng });
            },
            complete: () => {
                // uni.hideLoading();
            }
        })
    })
}
// 查询
const changePhone = (value: string) => {
    if (/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
        apiQueryPhone();
        isPhone.value = true
    } else {
        isPhone.value = false
    }
}
/** 
 * @property 内置方法
 */

onLoad((options) => {
    type.value = options?.type;
    if (type.value !== 'add') {
        colorId.value = markerStore.marker.showsize as string
    }
    aloneChecked.value = Boolean(uni.getStorageSync('aloneChecked'));
})
onUnload(() => {
    // markerStore.initMarker();
    markerStore.setPicList([]);
})
</script>
<template>
    <div class="w-[100vw] h-[100vh] pl-3 pr-3 pt-3 bg-[#f5f5f5]">
        <up-navbar title="编辑标记点信息" placeholder :autoBack="true">
        </up-navbar>
        <div class="w-[100%] p-l-2 bg-[#fff] b-rd-2 p-r-2">
            <up-form labelPosition="left" :model="markerStore.marker" labelWidth="150rpx" :rules="rules" ref="fromRef">
                <up-form-item label="标记类型">
                    <div class="frb pr-3" @click="isColor = true">
                        <AliIcon icon-name="icon-weizhi" font-size="40"
                            :color="colorList.find(item => item.id === colorId)?.color || 'red'" />
                        <up-icon name="arrow-right" size="14"></up-icon>
                    </div>
                </up-form-item>
                <up-form-item label="客户电话" prop="phone" borderBottom>
                    <up-input v-model="markerStore.marker.phone" border="none" placeholder="请输入客户电话" type="number"
                        maxlength="11" @change="changePhone"></up-input>
                </up-form-item>
                <up-form-item label="客户姓名" borderBottom prop="name">
                    <up-input v-model="markerStore.marker.name" border="none" placeholder="请输入客户姓名"
                        :disabled="!isPhone && colorId !== '1' && type !== 'applyForChanges'"
                        disabledColor="#f2f2f2"></up-input>
                </up-form-item>
                <up-form-item label="名称" borderBottom prop="alias">
                    <up-input v-model="markerStore.marker.alias" border="none" placeholder="请输入标记点名称"
                        :disabled="!isPhone && colorId !== '1' && type !== 'applyForChanges'"
                        disabledColor="#f2f2f2"></up-input>
                </up-form-item>
                <up-form-item label="地址" borderBottom>
                    <up-input v-model="markerStore.marker.toponym" border="none" placeholder="请输入地址"
                        disabledColor="#f2f2f2"></up-input>
                </up-form-item>

            </up-form>
            <div class="w-[100%] text-center c-red font-size-28 p-2" v-if="isQuerUser === 'false' && colorId !== '1'">
                注：未通过手机号查询出该店主信息</div>
        </div>
        <div class=" bg-[#fff] b-rd-2 p-l-2 mt-2">
            <up-form :labelStyle="{
                marginBottom: '20rpx'
            }">
                <up-form-item label="上传图片" labelPosition="top" labelWidth="200">
                    <up-upload :fileList="markerStore.picList" @afterRead="afterRead" @delete="deletePic" name="pic"
                        multiple :maxCount="3" :maxSize="2097152" @oversize="oversize" capture="camera"></up-upload>
                </up-form-item>
            </up-form>
        </div>
        <div class="mt-4 h-88">
            <Bottom :text="type === 'applyForChanges' ? '申请变更' : '保存'" @click="addMarker" />
        </div>
        <div class="fixed bottom-50 left-[50%] font-size-20 w-[100%] fc" style="transform: translateX(-50%);">
            <up-checkbox :customStyle="{ marginRight: '8px' }" v-model:checked="aloneChecked" usedAlone
                shape="circle" />
            添加之前请同意 <text style="color: #275EFF;" @click="navigateTo('/pages/policy/index')">《用户隐私政策和用户服务协议》</text>
        </div>
    </div>
    <up-picker :show="isShowSize" :columns="columns" keyName="label" @cancel="isShowSize = false"
        @confirm="clickConfirm"></up-picker>
    <up-popup :show="isColor" @close="isColor = false" mode="center" round="8" :safeAreaInsetBottom="false">
        <div class="w-700 p-3">
            <div class="flex pl-2 pr-2">
                <!-- <image :src="`/static/${item.color}.png`" v-for="item in colorList" :key="item.id" class="w-90 b-rd-2" /> -->
                <div class="ml-3 flex-col" v-for="item in colorList" :key="item.id" @click="colorId = item.id">
                    <div class="w-80 h-80 b-rd-1 fc " :style="{
                        background: item.id === colorId ? '#EBF6FF' : '#f2f2f2',
                        border: item.id === colorId ? '2rpx solid #0091FF' : 'none'
                    }">
                        <AliIcon icon-name="icon-weizhi" font-size="40" :color="item.color" />
                    </div>
                    <text class="font-size-24" v-if="item.id === '0'">合作店</text>
                    <text class="font-size-24" v-if="item.id === '1'">未合作</text>
                    <text class="font-size-24" v-if="item.id === '2'">意向客户</text>
                </div>

            </div>
            <div class="w-[100%] h-68 pl-3 pr-3 mt-10">
                <Bottom @click="isColor = false" />
            </div>
        </div>
    </up-popup>

</template>
<style lang="scss" scoped>
:deep(.u-cell__body) {
    padding: 0 20rpx 0 0 !important;
}
</style>